package com.xmb.wpclient.controller;


import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.xmb.wpclient.cache.CommonCache;
import com.xmb.wpclient.constant.*;
import com.xmb.wpclient.entity.*;
import com.xmb.wpclient.service.*;
import com.xmb.wpclient.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author huangping
 * @since 2021-05-28
 */
@Controller
@RequestMapping("/manage/common")
@Slf4j
public class CommonController {

	@Autowired
	public CommonCache commonCache;

	@Autowired
	public IBaseCommonConstantService iBaseCommonConstantService;

	@Autowired
	public IBaseCommonDataDictionaryAndSetService iBaseCommonDataDictionaryAndSetService;

	@Autowired
	public IBaseCommonQueryTableService iBaseCommonQueryTableService;

	@Autowired
	public ISysRoleService iSysRoleService;

	@Autowired
	public ISysUserService iSysUserService;

	public static final String enclosureFilePath = "D://CRM附件";
	
	/**
	 * 主页
	 * @return
	 */
	@GetMapping("/index/{url}")
	public String index(@PathVariable("url") String url, Model model) throws Exception {
		BaseEntry entry = commonCache.init(url);
		/**加载页面table表头*/
		List<BaseCommonDataDictionaryAndSet> colsList = entry.getSetList().stream().filter(item -> item.getDefaultShow()).collect(Collectors.toList());
		List<Map<String,Object>> cols = new ArrayList<>();
		Map<String,Object> checkboxMap = new HashMap<>();
		checkboxMap.put("type", "checkbox");
		cols.add(checkboxMap);
		for(BaseCommonDataDictionaryAndSet col : colsList){
			Map<String,Object> colMap = new HashMap<>();
			if(col.getQueryConstantId() != null){
				List<BaseCommonQueryTable> list = iBaseCommonQueryTableService.list(new LambdaQueryWrapper<BaseCommonQueryTable>()
						.eq(BaseCommonQueryTable::getDictionaryId, col.getId()));
				for(BaseCommonQueryTable queryTable : list){
					BaseCommonDataDictionaryAndSet set = iBaseCommonDataDictionaryAndSetService.getOne(new LambdaQueryWrapper<BaseCommonDataDictionaryAndSet>()
							.eq(BaseCommonDataDictionaryAndSet::getConstantId, col.getQueryConstantId()).eq(BaseCommonDataDictionaryAndSet::getTableField, queryTable.getQueryField()));
					colMap.put("field", col.getEntityField()+"_"+queryTable.getQueryField());
					colMap.put("title", col.getFieldExplain());
					colMap.put("minWidth", set.getFieldExplain().length()<3?80:set.getFieldExplain().length()<5?120:set.getFieldExplain().length()<7?140:150);
				}
			}else{
				colMap.put("field", col.getEntityField());
				colMap.put("title", col.getFieldExplain());
				colMap.put("minWidth", col.getFieldExplain().length()<3?80:col.getFieldExplain().length()<5?120:col.getFieldExplain().length()<7?140:150);
			}
			cols.add(colMap);
		}
		/**加载页面table查询条件*/
		List<BaseCommonDataDictionaryAndSet> criteriaList = entry.getSetList().stream().filter(item -> (item.getQueryCriteria() != null && item.getQueryCriteria())).collect(Collectors.toList());
		List<Map<String,Object>> dataFields = new ArrayList<>();
		Map<String, List<Map>> querySelectlist = new HashMap<>();
		for(BaseCommonDataDictionaryAndSet criteria : criteriaList){
			Map<String,Object> criteriaMap = new HashMap<>();
			criteriaMap.put("field", criteria.getTableField());
			criteriaMap.put("title", criteria.getFieldExplain());
			if(criteria.getQueryCriteriaType().equals(QueryTypeConstant.文本框.getCode())){
				criteriaMap.put("edit", "text");
			}else if(criteria.getQueryCriteriaType().equals(QueryTypeConstant.枚举下拉框.getCode())){
				criteriaMap.put("ops", "equal");
				criteriaMap.put("edit", "select");
				String[] split = criteria.getEnumList().split(";");
				List<Map> listMap = new ArrayList<>();
				for(String s : split){
					Map m = new HashMap();
					m.put("label",s.split("-")[0]);
					m.put("value",s.split("-")[1]);
					listMap.add(m);
				}
				querySelectlist.put(criteria.getEntityField()+"Templet", listMap);
				criteriaMap.put("templet", "#"+criteria.getEntityField()+"Templet");
			}else if(criteria.getQueryCriteriaType().equals(QueryTypeConstant.联表下拉框.getCode())){
				criteriaMap.put("ops", "equal");
				criteriaMap.put("edit", "select");
				BaseCommonConstant constant = iBaseCommonConstantService.getById(criteria.getQueryConstantId());
				BaseEntry queryEntry = commonCache.init(constant.getUrl());
				List<Object> list = queryEntry.getIService().list();
				List<Map> listMap = new ArrayList<>();
				for(Object o : list){
					Map m = new HashMap();
					m.put("label", BeanUtil.getMethod(o,criteria.getAssociatedFiled()).toString());
					m.put("value",BeanUtil.getMethod(o,StrUtil.toCamelCase(criteria.getQueryTableList().get(0).getQueryField())));
					listMap.add(m);
				}
				querySelectlist.put(criteria.getEntityField()+"Templet", listMap);
				criteriaMap.put("templet", "#"+criteria.getEntityField()+"Templet");
			}
			dataFields.add(criteriaMap);
		}
		Map<String, Object> map = new HashMap<>();
		map.put("url", url);
		map.put("cols", cols);
		map.put("dataFields", dataFields);
		model.addAttribute("obj", map);
		model.addAttribute("querySelectlist", querySelectlist);
		return url+"/index";
	}
	
	/**
	 * 添加导航
	 * @param url
	 * @param model
	 * @return
	 */
	@GetMapping("/addHtml/{url}")
	public String addHtml(@PathVariable("url") String url, Model model) throws Exception {
		List<Map<String,Object>> mapList = new ArrayList<>();
		BaseEntry entry = commonCache.init(url);
		addAndEditHtml(mapList, entry);
		model.addAttribute("obj", mapList);
		return url+"/add";
	}
	
	/**
	 * 编辑导航
	 * @param id
	 * @param model
	 * @return
	 */
	@GetMapping("/editHtml/{url}/{id}")
	public String editHtml(@PathVariable("url") String url, @PathVariable("id") String id ,Model model) throws Exception {
		List<Map<String,Object>> mapList = new ArrayList<>();
		BaseEntry entry = commonCache.init(url);
		addAndEditHtml(mapList, entry);
		model.addAttribute("obj", mapList);
		model.addAttribute("url", url);
		model.addAttribute("id", id);
		return url+"/update";
	}

	@GetMapping("/info/{url}/{id}")
	@ResponseBody
	public Object info(@PathVariable("url") String url, @PathVariable("id") String id) throws Exception {
		//得到枚举里面具体的service
		IService<Object> iService = commonCache.init(url).getIService();
		return iService.getById(id);
	}
	
	@PostMapping("/list/{url}")
	@ResponseBody
	public LayTableR list(@PathVariable("url") String url, Integer page, Integer limit, String master) throws Exception {
		QueryWrapper<Object> ew = ConditionUtil.convert(master, new QueryWrapper<Object>());
		BaseEntry baseEntry = commonCache.init(url);
		IService<Object> iService = baseEntry.getIService();
		for(BaseCommonDataDictionaryAndSet set : baseEntry.getSetList()){
			if(set.getSort() != null){
				if(set.getSort()){
					ew.orderByAsc(set.getTableField());
				}else{
					ew.orderByDesc(set.getTableField());
				}
			}
		}
		Page<Object> selectPage = iService.page(new Page<>(page, limit), ew);
		List<BaseCommonDataDictionaryAndSet> collect = baseEntry.getSetList().stream().filter(e -> e.getQueryConstantId() != null).collect(Collectors.toList());
		List<Map> resultList = dataTransfer(selectPage.getRecords(), collect);

		return LayTableR.result(0, selectPage.getTotal(), resultList);
	}

	@PostMapping("/add")
	@ResponseBody
	public R add(String url, String obj) {
		try {
			BaseEntry baseEntry = commonCache.init(url);
			setObj(baseEntry,obj);
			IService<Object> iService = baseEntry.getIService();
			List<BaseCommonDataDictionaryAndSet> collect = baseEntry.getSetList().stream().filter(e -> e.getUniqueness()).collect(Collectors.toList());
			if(collect.size() > 0){
				QueryWrapper<Object> ew = new QueryWrapper<>();
				for(BaseCommonDataDictionaryAndSet set : collect){
					ew.eq(set.getTableField(), BeanUtil.getMethod(baseEntry.getData(), set.getEntityField()));
				}
				Object object = iService.getOne(ew);
				if(object != null) {
					return R.error("请勿重复添加");
				}
			}
			for(BaseCommonDataDictionaryAndSet set : baseEntry.getSetList()){
				if(StringUtils.isNotEmpty(set.getDefaultValue())){
					if(set.getDefaultValue().equals(DefaultValueConstant.user.getCode())){
						BeanUtil.setMethod(baseEntry.getData(), set.getEntityField(), ShiroUtil.getUserId());
					}else if(set.getDefaultValue().equals(DefaultValueConstant.date.getCode())){
						BeanUtil.setMethod(baseEntry.getData(), set.getEntityField(), new Date());
					}else if(set.getDefaultValue().equals(DefaultValueConstant.disable.getCode())){
						BeanUtil.setMethod(baseEntry.getData(), set.getEntityField(), false);
					}
				}
			}
			iService.save(baseEntry.getData());
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("系统异常");
		}
		return R.ok();
	}
	

	@PostMapping("/update")
	@ResponseBody
	public R update(String url, String obj) {
		try {
			BaseEntry baseEntry = commonCache.init(url);
			setObj(baseEntry,obj);
			IService<Object> iService = baseEntry.getIService();
			List<BaseCommonDataDictionaryAndSet> collect = baseEntry.getSetList().stream().filter(e -> e.getUniqueness()).collect(Collectors.toList());
			if(collect.size() > 0){
				QueryWrapper<Object> ew = new QueryWrapper<>();
				for(BaseCommonDataDictionaryAndSet set : collect){
					ew.eq(set.getTableField(), BeanUtil.getMethod(baseEntry.getData(), set.getEntityField()));
				}
				Object object = iService.getOne(ew);
				if(object != null && !BeanUtil.getMethod(object, "id").equals(BeanUtil.getMethod(baseEntry.getData(), "id"))) {
					return R.error("唯一性冲突");
				}
			}
			iService.updateById(baseEntry.getData());
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("系统异常");
		}
		return R.ok();
	}
	
	@PostMapping("/delete/{url}")
	@ResponseBody
	public R update(@PathVariable("url") String url, @RequestBody List<String> ids) {
		String msg = "";
		try {
			BaseEntry baseEntry = commonCache.init(url);
			List<BaseCommonDataDictionaryAndSet> setList = iBaseCommonDataDictionaryAndSetService.list(new LambdaQueryWrapper<BaseCommonDataDictionaryAndSet>()
					.eq(BaseCommonDataDictionaryAndSet::getQueryConstantId, baseEntry.getConstant().getId()));
			IService<Object> iService = baseEntry.getIService();
			if(setList.size() > 0){
				Iterator<String> iterator = ids.iterator();
				w:
				while (iterator.hasNext()){
					String id = iterator.next();
					Object o = iService.getById(id);
					for(BaseCommonDataDictionaryAndSet set : baseEntry.getSetList()){
						if(set.getDisable()){
							if(!(Boolean) BeanUtil.getMethod(o, set.getEntityField())){
								msg = msg + "处于启用状态的数据无法删除，请先禁用后再操作";
								iterator.remove();
								continue w;
							}
						}
					}

					boolean flag = false;
					for(BaseCommonDataDictionaryAndSet set : setList){
						BaseCommonConstant constant = iBaseCommonConstantService.getById(set.getConstantId());
						BaseEntry entry = commonCache.init(constant.getUrl());
						IService<Object> iOtherService = entry.getIService();
						long count = iOtherService.count(new QueryWrapper<>().eq(set.getTableField(), id));
						if(count != 0){
							flag = true;
							msg = msg + constant.getName()+"表中已引用id为："+id+"的数据，要删除则需先删除"+constant.getName()+"表引用数据";
						}
					}
					if(flag){
						iterator.remove();
					}
				}
			}
			if(ids.size() > 0){
				iService.removeBatchByIds(ids);
			}else{
				return R.error(msg);
			}
		} catch (Exception e) {
			return R.error("系统异常");
		}
		return R.ok(msg);
	}

	@PostMapping("/disable/{url}")
	@ResponseBody
	@Transactional
	public R disable(@PathVariable("url") String url, @RequestBody List<String> ids) {
		try {
			BaseEntry baseEntry = commonCache.init(url);
			IService<Object> iService = baseEntry.getIService();
			List<BaseCommonDataDictionaryAndSet> collect = baseEntry.getSetList().stream().filter(e -> e.getDisable()).collect(Collectors.toList());
			if(collect.size() != 1){
				return R.error("当前表单并未设置禁用字段，请到字段&设置中去设置");
			}
			for(String id : ids){
				Object obj = iService.getById(id);
				boolean disable = (boolean) BeanUtil.getMethod(obj, collect.get(0).getEntityField());
				BeanUtil.setMethod(obj, collect.get(0).getEntityField(), !disable);
				iService.updateById(obj);
			}
		} catch (Exception e) {
			return R.error("系统异常");
		}
		return R.ok();
	}

	@RequestMapping("/download")
	@ResponseBody
	public void download(String url, String condition, HttpServletResponse response) {
		List<Map> conditionList = JSON.parseArray(condition, Map.class);
		try {
			BaseEntry baseEntry = commonCache.init(url);
			List<BaseCommonDataDictionaryAndSet> colsList = baseEntry.getSetList().stream().filter(item -> item.getDefaultShow()).collect(Collectors.toList());
			String queryCriteriaStr = "【查询条件】";
			QueryWrapper qw = new QueryWrapper();
			if(conditionList.size() > 0){
			    for(Map m : conditionList){
                    BaseCommonDataDictionaryAndSet set = colsList.stream().filter(item -> item.getTableField().equals(m.get("field"))).findFirst().get();
                    queryCriteriaStr = queryCriteriaStr+set.getFieldExplain()+": "+m.get("value")+";   ";
                    switch (m.get("type").toString()){
                        case "equal":
                            qw.eq(m.get("field").toString(), m.get("value"));
                            break;
                        case "like":
                            qw.like(m.get("field").toString(), m.get("value"));
                            break;
                        case "unequal":
                            qw.ne(m.get("field").toString(), m.get("value"));
                            break;
                        case "empty":
                            qw.isNull(m.get("field").toString());
                            break;
                        case "notempty":
                            qw.isNotNull(m.get("field").toString());
                            break;
                        case "between":
                            qw.between(m.get("field").toString(), m.get("left"), m.get("right"));
                            break;
                        case "greater_than":
                            qw.gt(m.get("field").toString(), m.get("value"));
                            break;
                        case "less_than":
                            qw.lt(m.get("field").toString(), m.get("value"));
                            break;
                        case "start":
                            qw.likeLeft(m.get("field").toString(), m.get("value"));
                            break;
                        case "end":
                            qw.likeRight(m.get("field").toString(), m.get("value"));
                            break;
                    }
                }
            }else{
                queryCriteriaStr = queryCriteriaStr+"无查询条件，查询全表";
            }
			//excel表头
			List<TitleEntity> titleList=new ArrayList<>();
			titleList.add(new TitleEntity("0",null,baseEntry.getConstant().getName()+"表",null));
			titleList.add(new TitleEntity("1","0",queryCriteriaStr,null));
			for(int i=0; i<colsList.size(); i++){
                if(colsList.get(i).getQueryConstantId() != null){
                    List<BaseCommonQueryTable> list = iBaseCommonQueryTableService.list(new LambdaQueryWrapper<BaseCommonQueryTable>()
                            .eq(BaseCommonQueryTable::getDictionaryId, colsList.get(i).getId()));
                    for(BaseCommonQueryTable queryTable : list){
                        BaseCommonDataDictionaryAndSet set = iBaseCommonDataDictionaryAndSetService.getOne(new LambdaQueryWrapper<BaseCommonDataDictionaryAndSet>()
                                .eq(BaseCommonDataDictionaryAndSet::getConstantId, colsList.get(i).getQueryConstantId()).eq(BaseCommonDataDictionaryAndSet::getTableField, queryTable.getQueryField()));
                        titleList.add(new TitleEntity(String.valueOf(i+2),"1",colsList.get(i).getFieldExplain(),colsList.get(i).getEntityField()+"_"+queryTable.getQueryField()));
                    }
                }else{
                    titleList.add(new TitleEntity(String.valueOf(i+2),"1",colsList.get(i).getFieldExplain(),colsList.get(i).getEntityField()));
                }

            }

			//excel数据
			List<Object> list = baseEntry.getIService().list(qw);
            List<BaseCommonDataDictionaryAndSet> collect = colsList.stream().filter(e -> e.getQueryConstantId() != null).collect(Collectors.toList());
			List<Map> resultMap = dataTransfer(list, collect);
//			Map<String, Object> map = new HashMap<String, Object>();
//			map.put("bm","合计");
//			list = ListRepeatUtil.getTotal(list, map);
//			List<Object> coverList = BeanUtil.fmtMicrometer(list,HashMap.class);
//			List<Map<String,String>> rowList = new ArrayList<Map<String,String>>();
//			for (Object object : coverList) {
//				rowList.add((Map<String, String>) object);
//			}
			ExcelTool excelTool = new ExcelTool(baseEntry.getConstant().getName()+"表",20,20);
			List<Column>  titleData = excelTool.columnTransformer(titleList,"t_id","t_pid","t_content","t_fielName","0");
			response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(baseEntry.getConstant().getName()+"表"+DateUtil.currentYYMMDD()+".xlsx", "utf-8"));
			excelTool.exportExcel(titleData,resultMap, response.getOutputStream(),true,true);
		}catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 税率档案导入
	 * @param data
	 * @return
	 */
	@RequestMapping("/upload")
	@ResponseBody
	public R upload(String url, String data) {
		String msg = "";
		try {
			BaseEntry baseEntry = commonCache.init(url);
			setObj(baseEntry,data);
			IService<Object> iService = baseEntry.getIService();
			Iterator<Object> iterator = ((List<Object>) baseEntry.getData()).iterator();
			while (iterator.hasNext()) {
				Object object = iterator.next();

				List<BaseCommonDataDictionaryAndSet> collect = baseEntry.getSetList().stream().filter(e -> e.getUniqueness()).collect(Collectors.toList());
				if(collect.size() > 0){
					QueryWrapper<Object> ew = new QueryWrapper<>();
					for(BaseCommonDataDictionaryAndSet set : collect){
						ew.eq(set.getTableField(), BeanUtil.getMethod(object, set.getEntityField()));
					}
					Object obj = iService.getOne(ew);
					if(obj != null) {
						iterator.remove();
						for(BaseCommonDataDictionaryAndSet set : collect){
							msg += set.getFieldExplain()+":"+BeanUtil.getMethod(obj, set.getEntityField())+"已存在!<br/>";
						}
						continue;
					}
				}
			}
			if(((List<Object>) baseEntry.getData()).size() > 0) {
				iService.saveBatch((List<Object>) baseEntry.getData());
				if(msg != "") {
					msg += "本次导入的是未重复的数据，以上重复的数据已被过滤！";
				}
			}else {
				if(msg != "") {
					msg += "本次导入的全是重复的数据！";
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("系统异常");
		}
		return R.ok(msg);
	}
	
	private BaseEntry setObj(BaseEntry baseEntry, String obj) throws Exception {
		if(obj.contains("[{")) {
			baseEntry.setData(BeanUtil.parseObjToList(obj, Class.forName(baseEntry.getEntityClass())));
		}else {
			baseEntry.setData(BeanUtil.parseObjToBean(obj, Class.forName(baseEntry.getEntityClass())));
		}
		return baseEntry;
	}

	private void addAndEditHtml(List<Map<String,Object>> mapList, BaseEntry entry) throws Exception {
		for(BaseCommonDataDictionaryAndSet set : entry.getSetList()){
			if(StringUtils.isEmpty(set.getDefaultValue())){
				Map<String,Object> map = new HashMap<>();
				if(set.getQueryConstantId() != null){
					map.put("type", "combobox");
					map.put("data", set);
					BaseCommonConstant constant = iBaseCommonConstantService.getById(set.getQueryConstantId());
					BaseEntry queryEntry = commonCache.init(constant.getUrl());
					List<Object> list = new ArrayList<>();
					for(BaseCommonDataDictionaryAndSet querySet : queryEntry.getSetList()){
						if(querySet.getDisable()){
							list = queryEntry.getIService().list(new QueryWrapper<>().eq(querySet.getTableField(), false));
						}
					}
					List<Map> listMap = new ArrayList<>();
					for(Object o : list){
						Map m = new HashMap();
						m.put("label",BeanUtil.getMethod(o,set.getAssociatedFiled()).toString());
						m.put("value",BeanUtil.getMethod(o,set.getQueryTableList().get(0).getQueryField()));
						listMap.add(m);
					}
					map.put("list", listMap);
					mapList.add(map);
				}else{
					if(StringUtils.isNotEmpty(set.getQueryCriteriaType()) && set.getQueryCriteriaType().equals(QueryTypeConstant.枚举下拉框.getCode())){
						String[] split = set.getEnumList().split(";");
						List<Map> listMap = new ArrayList<>();
						for(String s : split){
							Map m = new HashMap();
							m.put("label",s.split("-")[0]);
							m.put("value",s.split("-")[1]);
							listMap.add(m);
						}
						map.put("type", "combobox");
						map.put("data", set);
						map.put("list", listMap);
						mapList.add(map);
					}else if(set.getFieldType().equals("varchar") || set.getFieldType().equals("char")){
						map.put("type", "textbox");
						map.put("data", set);
						mapList.add(map);
					}else if(set.getFieldType().equals("int")){
						map.put("type", "numberbox");
						map.put("data", set);
						mapList.add(map);
					}else if(set.getFieldType().equals("decimal")){
						map.put("type", "numberbox");
						map.put("data", set);
						mapList.add(map);
					}else if(set.getFieldType().equals("datetime")){
						map.put("type", "datebox");
						map.put("data", set);
						mapList.add(map);
					}else if(set.getFieldType().equals("bit")){
						map.put("type", "combobox");
						map.put("data", set);
						List<Map> listMap = new ArrayList<>();
						Map m = new HashMap();
						m.put("label","true");
						m.put("value","是");
						listMap.add(m);
						Map m2 = new HashMap();
						m2.put("label","false");
						m2.put("value","否");
						listMap.add(m2);
						map.put("list", listMap);
						mapList.add(map);
					}
				}
			}
		}
	}

	public List<Map> dataTransfer(List<Object> objList, List<BaseCommonDataDictionaryAndSet> collect) throws Exception {
        List<Map> resultList = new ArrayList<>();
        for(Object o : objList){
            Map<String, String> map = BeanUtils.describe(o);
            BeanUtil.dateFormat(o, map);
            resultList.add(map);
        }
        for(BaseCommonDataDictionaryAndSet set : collect){
            BaseCommonConstant constant = iBaseCommonConstantService.getOne(new LambdaQueryWrapper<BaseCommonConstant>().eq(BaseCommonConstant::getId, set.getQueryConstantId()));
            BaseEntry entry = commonCache.init(constant.getUrl());
            IService<Object> constrastService = entry.getIService();
            for(Map map : resultList){
                Object contrastObj = constrastService.getOne(new QueryWrapper<>().eq(set.getAssociatedFiled(), map.get(set.getEntityField()))
						.or().eq(set.getQueryTableList().get(0).getQueryField(), map.get(set.getEntityField())));
                for(BaseCommonQueryTable queryTable : set.getQueryTableList()){
                    map.put(set.getEntityField()+"_"+queryTable.getQueryField(),contrastObj == null?"":BeanUtil.getMethod(contrastObj, StrUtil.toCamelCase(queryTable.getQueryField())));
                }
            }
        }
        return resultList;
    }


	public Set<Long> getUserIdByRole(String roleId) {
		Set<Long> userIds = new HashSet<>();
		List<SysRole> roleList = iSysRoleService.list(new LambdaQueryWrapper<SysRole>().eq(SysRole::getPid, roleId));
		for(SysRole role : roleList){
			List<SysUser> userList = iSysUserService.list(new LambdaQueryWrapper<SysUser>().select(SysUser::getId).eq(SysUser::getRoleId, role.getId()));
			userIds.addAll(userList.stream().map(SysUser::getId).collect(Collectors.toSet()));
			long count = iSysRoleService.count(new LambdaQueryWrapper<SysRole>().eq(SysRole::getPid, role.getId()));
			if(count != 0){
				userIds.addAll(getUserIdByRole(role.getId()));
			}
		}
		return userIds;
	}
}

